package com.yxw.live_vod_boot.service.impl;

import com.yxw.live_vod_backend_facade.dto.ProductFeignQueryDTO;
import com.yxw.live_vod_backend_facade.feign.ProductFeignClient;
import com.yxw.live_vod_backend_facade.vo.ProductSpecificationVO;
import com.yxw.live_vod_backend_facade.vo.ProductVO;
import com.yxw.live_vod_boot.dto.AddVodProductDto;
import com.yxw.live_vod_boot.dto.VodProductClickDto;
import com.yxw.live_vod_boot.entity.YxVodProductEntity;
import com.yxw.live_vod_boot.mapper.VodProductClickMapper;
import com.yxw.live_vod_boot.mapper.VodProductMapper;
import com.yxw.live_vod_boot.service.ProductService;
import com.yxw.live_vod_boot.utils.RedisManager;
import com.yxw.live_vod_boot.utils.UserUtil;
import com.yxw.live_vod_facade.vo.VodProductClickVo;
import com.yxw.yxnet_cd_center.common.constant.CommonConstant;
import com.yxw.yxnet_cd_center.common.constant.RedisIdConstant;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private VodProductMapper vodProductMapper;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RedisManager redisManager;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private VodProductClickMapper vodProductClickMapper;

    @Override
    public BaseResult<ProductVO> getProductById(Long productId) {
        return productFeignClient.getProductById(productId);
    }

    @Override
    public BaseResult<PageVO<ProductVO>> getProductList(ProductFeignQueryDTO queryDTO) {
        return productFeignClient.getProductList(queryDTO);
    }

    @Override
    public BaseResult<List<ProductSpecificationVO>> getProductSpecificationById(Long productId) {
        return productFeignClient.getProductSpecificationById(productId);
    }

    @Override
    public BaseResult<List<ProductVO>> getProductByNum(String productSeriesNum) {
        return productFeignClient.getProductByNum(productSeriesNum);
    }

    /**
     * 点播视频添加在售商品
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addVodProduct(AddVodProductDto dto) {
        //查询商品详情
        BaseResult<ProductVO> result = productFeignClient.getProductById(dto.getProductId());
        ProductVO proVo = result.getData();
        if(null==proVo){
            throw new BaseException("查询商品信息失败");
        }
        YxVodProductEntity entity = new YxVodProductEntity();
        entity.setProductId(proVo.getProductId());
        entity.setProductName(proVo.getProductName());
        if(null!=proVo.getProductMasterPic()){
            entity.setProductMasterPic(proVo.getProductMasterPic()[0]);
        }
        if(null!=proVo.getProductDetailPic()){
            entity.setProductDetailPic(proVo.getProductDetailPic()[0]);
        }
        entity.setCreateId(userUtil.getLoginUserId());
        entity.setCreateName(userUtil.getLoginName());
        entity.setCreateTime(new Date());
        entity.setStatus(CommonConstant.ONE);
        entity.setReviewVideoId(dto.getReviewVideoId());
        entity.setTotalCnt(proVo.getTotalCnt());
        entity.setPrice(proVo.getProductPrice().doubleValue());
        vodProductMapper.insert(entity);
    }

    /**
     * 点播商品记录点击次数
     * 放入redis缓存，通过定时任务取
     * @param dto
     */
    @Override
    public void addVodProductClickInfo(VodProductClickDto dto) {
        VodProductClickVo vo = new VodProductClickVo();
        vo.setUserId(userUtil.getLoginUserId());
        vo.setUserName(userUtil.getLoginName());
        vo.setVideoId(dto.getVideoId());
        vo.setProductId(dto.getProductId());
        vo.setClickTime(new Date());
        redisManager.addBySet(RedisIdConstant.VOD_PRODUCT_CLICK,vo);
    }

    /**
     * 定时任务将点播商品详情存入数据库
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addVodProductClickJob() {
        //查询缓存
        Set<VodProductClickVo> clickVoSet = redisTemplate.opsForSet().members(RedisIdConstant.VOD_PRODUCT_CLICK);
        //删除缓存数据
        redisTemplate.delete(RedisIdConstant.VOD_PRODUCT_CLICK);
        if (null != clickVoSet && !clickVoSet.isEmpty()) {
            //批量保存，每次最多保存1000条
            int totalSize = clickVoSet.size();
            int sizePage = 1000;
            int totalCnt = totalSize % sizePage == 0 ? totalSize / sizePage : totalSize / sizePage + 1;
            for (int i = 0; i < totalCnt; i++) {
                List<VodProductClickVo> clickVoList = clickVoSet.stream().skip(i * sizePage).limit(sizePage).collect(Collectors.toList());
                try{
                    //批量保存
                    vodProductClickMapper.addProductClickByBatch(clickVoList);
                }catch (Exception e){
                    log.error("保存点播商品点击详情失败{}",e.getMessage());
                }
            }
        }
    }
}
